package com.dragon.logical.service.auth.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.auth.IModRoleService;
import com.dragon.logical.service.auth.RoleService;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-12
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMapper mapper;

    @Autowired
    RoleDepartmentMapper roleDepartmentMapper;

    @Autowired
    AdminRoleMapper adminRoleMapper;

    @Autowired
    RoleMenuMapper roleMenuMapper;

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    IModRoleService modRoleService;

    @Autowired
    ModRoleMapper modRoleMapper;

    @Override
    public List<Role> getRoleList(String name){
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(name)){
            wrapper.lambda().like(Role::getRoleName,name);
        }
        List<Role> roles = mapper.selectList(wrapper);
        return roles;
    }

    @Override
    public void addRole(Role convert) {
        Role role = mapper.selectById(convert.getId());
        if (role != null){
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS);
        }
        convert.setCreateTime(DateUtil.date());
        mapper.insert(convert);
    }

    @Override
    public void updateRole(Role convert) {
        Role role = mapper.selectById(convert.getId());
        if (role == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        convert.setUpdateTime(DateUtil.date());
        mapper.updateById(convert);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Integer id) {
        Role role = mapper.selectById(id);
        if (role == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        // 查询用户是否有关联数据
        List<AdminRole> adminRoles = adminRoleMapper.selectAdminByRoleId(id);
        if (adminRoles.size() != 0){
            throw new CustomException(ResultCode.ROLE_DATA_IS_EXIT_ADMIN);
        }

        // 处理角色部门表
        LambdaQueryWrapper<RoleDepartment> rdWrapper = new QueryWrapper<RoleDepartment>().lambda().eq(RoleDepartment::getRoleId, role.getId());
        roleDepartmentMapper.delete(rdWrapper);
//        if ( roleDepartments.size() != 0 ){
//            throw new CustomException(ResultCode.ROLE_DATA_IS_EXIT_DEPARTMENT);
//        }

        // 处理角色菜单表
        QueryWrapper<RoleMenu> rmQueryWrapper = new QueryWrapper<>();
        rmQueryWrapper.lambda().eq(RoleMenu::getRoleId,role.getId());
        roleMenuMapper.delete(rmQueryWrapper);
//        if ( roleMenus.size() != 0 ){
//            throw new CustomException(ResultCode.ROLE_DATA_IS_EXIT_MENU);
//        }
        // 处理控制台关联表
        QueryWrapper<ModRole> modRoleQueryWrapper = new QueryWrapper<>();
        modRoleQueryWrapper.lambda().eq(ModRole::getRoleId,id);
        modRoleMapper.delete(modRoleQueryWrapper);

        mapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoles(List<Integer> ids){

        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Role::getId,ids);
        List<Role> roles = mapper.selectList(queryWrapper);
        if (roles.size() != ids.size()){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        // 用户角色表
        List<AdminRole> adminRoles = adminRoleMapper.selectAdminByRoleIds(ids);
        if (adminRoles.size() != 0){
            throw new CustomException(ResultCode.ROLE_DATA_IS_EXIT_ADMIN);
        }

        // 角色部门表
        QueryWrapper<RoleDepartment> rdQueryWrapper = new QueryWrapper<>();
        rdQueryWrapper.lambda().in(RoleDepartment::getRoleId,ids);
        roleDepartmentMapper.delete(rdQueryWrapper);

        // 角色菜单表
        QueryWrapper<RoleMenu> rmQueryWrapper = new QueryWrapper<>();
        rmQueryWrapper.lambda().in(RoleMenu::getRoleId,ids);
        roleMenuMapper.delete(rmQueryWrapper);

        // 处理控制台关联表
        QueryWrapper<ModRole> modRoleQueryWrapper = new QueryWrapper<>();
        modRoleQueryWrapper.lambda().in(ModRole::getRoleId,ids);
        modRoleMapper.delete(modRoleQueryWrapper);

        mapper.delete(queryWrapper);
    }

    @Override
    public void rolePermission(Integer roleId, Integer dateType,String menuIds,String departmentIds, String modIds){
        QueryWrapper<Role> rqw = new QueryWrapper<>();
        rqw.lambda().eq(Role::getId,roleId);
        Role role = mapper.selectOne(rqw);
        if (role == null) {
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }

        //删除菜单的所有权限
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.lambda().eq(RoleMenu::getRoleId,roleId);
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(roleMenuQueryWrapper);
        if(roleMenuList!=null){
            roleMenuMapper.delete(roleMenuQueryWrapper);
        }
        //菜单权限分配
        if(StrUtil.isNotBlank(menuIds)){
            List<String> stringList = Arrays.asList(menuIds.split(","));
            stringList.forEach(id -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(Integer.valueOf(id));
                roleMenuMapper.insert(roleMenu);
            });
        }


        // 设置数据权限
        menuMapper.selectList(null);
        role.setDataAuthType(dateType);
        mapper.updateById(role);
        //删除之前的role department关联数据
        QueryWrapper<RoleDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RoleDepartment::getRoleId,roleId);
        List<RoleDepartment> roleDepartments = roleDepartmentMapper.selectList(queryWrapper);
        if(roleDepartments!=null){
            roleDepartmentMapper.delete(queryWrapper);
        }
        // 选择部门可见
        if(dateType==4&&StrUtil.isNotBlank(departmentIds)){
            List<String> stringLists = Arrays.asList(departmentIds.split(","));
            stringLists.forEach(id->{
                RoleDepartment department = new RoleDepartment();
                department.setRoleId(roleId);
                department.setDepartmentId(Integer.valueOf(id));
                roleDepartmentMapper.insert(department);
            });
        }
        //选择模块
        modRoleService.chooseMod(roleId,modIds);
    }

    @Override
    public List<Integer> selectMenuList(Integer roleId){
        QueryWrapper<RoleMenu> roleMenuQueryWrapper = new QueryWrapper<>();
        roleMenuQueryWrapper.lambda().eq(RoleMenu::getRoleId,roleId).select(RoleMenu::getMenuId);
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(roleMenuQueryWrapper);
        return roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
    }

    @Override
    public List<Integer> selectDepartmentList(Integer roleId){
        QueryWrapper<RoleDepartment> roleDepartmentQueryWrapper = new QueryWrapper<>();
        roleDepartmentQueryWrapper.lambda().eq(RoleDepartment::getRoleId,roleId).select(RoleDepartment::getDepartmentId);
        List<RoleDepartment> roleDepartments = roleDepartmentMapper.selectList(roleDepartmentQueryWrapper);
        return roleDepartments.stream().map(RoleDepartment::getDepartmentId).collect(Collectors.toList());
    }
}
